var express = require('express');
var router = express.Router();
var ManagerModel = require('../models/manager');
var ApplicantModel = require('../models/applicant');
var nodeExcel = require('excel-export');
var conf = {};
conf.stylesXmlFile = "styles.xml";
conf.name = "whushandongSignupSheet";
conf.cols = [{
    caption: '姓名',
    type: 'string',
}, {
    caption: '性别',
    type: 'string',
}, {
    caption: '年级',
    type: 'string'
}, {
    caption: '地区',
    type: 'string'
}, {
    caption: '学部',
    type: 'string'
}, {
    caption: '手机号',
    type: 'string',
    width: 28
}, {
    caption: '邮箱',
    type: 'string',
    width: 28
}, {
    caption: '报名日期',
    type: 'string',
    width: 28
}, {
    caption: '是否缴费',
    type: 'string'
}];
router.get('/', function(req, res, next) {
    if (req.cookies.token) {
        ManagerModel.find({ token: req.cookies.token }, function(err, data) {
            if (data.length > 0) {
                ApplicantModel.find(function(err, data) {
                    if (err) {
                        return err;
                    }
                    conf.rows = [];
                    conf.rows = data.map(function(e) {
                        var date = new Date(e['date']);
                        var time = date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
                        return [e['name'], e['sex'], e['grade'], e['area'], e['department'], e['phone'], e['email'], time, e['isPayed'].toString()];
                    });
                    console.log(conf.rows);
                    var result = nodeExcel.execute(conf);
                    res.setHeader('Content-Type', 'application/vnd.openxmlformats');
                    res.setHeader("Content-Disposition", "attachment; filename=" + "whushandong.xlsx");
                    res.end(result, 'binary');
                })
            } else {
                res.redirect(302, 'login');
            }
        })
    } else {
        res.redirect(302, 'login');
    };
});

module.exports = router;